package com.itheima.easyexcel.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.itheima.easyexcel.listener.ExcelListener;
import com.itheima.easyexcel.mapper.UserMapper;
import com.itheima.easyexcel.pojo.TbUser;
import com.itheima.easyexcel.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@Service
public class UserServiceImpl  implements IUserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public void excelExport(HttpServletResponse response) throws IOException {
        //1.获取数据库表中的所有数据
        List<TbUser> userList = userMapper.findAll();
        //2.定义导出文件名称
        String fileName="用户名单";

        //3.设置响应对象
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition","attachment;filename="+new String(fileName.getBytes("gb2312"),"ISO8859-1")+".xls");
        //4.输出流和写入流
        ServletOutputStream out = response.getOutputStream();

        //写流，指定具体执行的class类
        ExcelWriter excelWriter = EasyExcel.write(out, TbUser.class).build();
        //设置sheet
        WriteSheet writeSheet=EasyExcel.writerSheet("sheet1").build();
        //执行写的过程
        excelWriter.write(userList,writeSheet);
        //写流完成，会自动关闭流
       excelWriter.finish();
    }
    //导出文件
    @Override
    public void excelImport(MultipartFile file) throws Exception {
        if(!file.getOriginalFilename().equals("用户名单.xls") && !file.getOriginalFilename().equals("用户名单.xlsx") ){
            return;
        }
        InputStream inputStream = new BufferedInputStream(file.getInputStream());
        //实例化实现了AnalysisEventListener接口的类
        ExcelListener excelListener = new ExcelListener(userMapper);
        //设置读取数据的工具类
        ExcelReader excelReader = EasyExcel.read(inputStream, TbUser.class, excelListener).build();
        //设置读取的sheet
        ReadSheet readSheet = EasyExcel.readSheet(0).build();
        //执行读过程
        excelReader.read(readSheet);
        //读流完成，会自动关闭流
        excelReader.finish();
    }
}
